package com.fortune.app.fragments;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.TimePicker;
import androidx.fragment.app.Fragment;

import com.fortune.app.R;
import com.fortune.app.FortuneApplication;
import com.fortune.app.utils.NotificationHelper;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

/**
 * 个人资料Fragment，提供用户信息设置和应用偏好
 */
public class ProfileFragment extends Fragment {
    private EditText etName;
    private EditText etBirthDate;
    private Button btnSelectDate;
    private EditText etGender;
    private Button btnSaveUserInfo;
    private TextView tvUserInfoStatus;
    
    private Switch switchNotification;
    private TimePicker timePicker;
    private Button btnSaveSettings;
    private TextView tvSettingsStatus;
    
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_profile, container, false);
        
        // 初始化用户信息视图
        etName = view.findViewById(R.id.et_name);
        etBirthDate = view.findViewById(R.id.et_birth_date);
        btnSelectDate = view.findViewById(R.id.btn_select_date);
        etGender = view.findViewById(R.id.et_gender);
        btnSaveUserInfo = view.findViewById(R.id.btn_save_user_info);
        tvUserInfoStatus = view.findViewById(R.id.tv_user_info_status);
        
        // 初始化设置视图
        switchNotification = view.findViewById(R.id.switch_notification);
        timePicker = view.findViewById(R.id.time_picker);
        btnSaveSettings = view.findViewById(R.id.btn_save_settings);
        tvSettingsStatus = view.findViewById(R.id.tv_settings_status);
        
        // 设置日期选择按钮点击事件
        btnSelectDate.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showDatePickerDialog();
            }
        });
        
        // 设置保存用户信息按钮点击事件
        btnSaveUserInfo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                saveUserInfo();
            }
        });
        
        // 设置保存设置按钮点击事件
        btnSaveSettings.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                saveSettings();
            }
        });
        
        // 加载用户信息
        loadUserInfo();
        
        // 加载设置
        loadSettings();
        
        return view;
    }
    
    /**
     * 显示日期选择对话框
     */
    private void showDatePickerDialog() {
        Calendar calendar = Calendar.getInstance();
        int year = calendar.get(Calendar.YEAR);
        int month = calendar.get(Calendar.MONTH);
        int day = calendar.get(Calendar.DAY_OF_MONTH);
        
        DatePickerDialog datePickerDialog = new DatePickerDialog(
                getActivity(),
                new DatePickerDialog.OnDateSetListener() {
                    @Override
                    public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
                        // 月份从0开始，需要+1
                        String birthDate = String.format(Locale.CHINA, "%d-%02d-%02d", year, month + 1, dayOfMonth);
                        etBirthDate.setText(birthDate);
                    }
                },
                year, month, day);
        
        // 设置最大日期为今天
        datePickerDialog.getDatePicker().setMaxDate(System.currentTimeMillis());
        
        datePickerDialog.show();
    }
    
    /**
     * 保存用户信息
     */
    private void saveUserInfo() {
        String name = etName.getText().toString().trim();
        String birthDate = etBirthDate.getText().toString().trim();
        String gender = etGender.getText().toString().trim();
        
        if (birthDate.isEmpty()) {
            etBirthDate.setError("请选择出生日期");
            return;
        }
        
        // 保存用户信息
        FortuneApplication app = FortuneApplication.getInstance();
        app.saveUserName(name);
        app.saveUserBirthDate(birthDate);
        app.saveUserGender(gender);
        
        // 更新状态
        tvUserInfoStatus.setText("用户信息已保存");
        tvUserInfoStatus.setVisibility(View.VISIBLE);
        
        // 延迟隐藏状态
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                if (isAdded()) {
                    tvUserInfoStatus.setVisibility(View.GONE);
                }
            }
        }, 3000);
    }
    
    /**
     * 保存设置
     */
    private void saveSettings() {
        boolean notificationsEnabled = switchNotification.isChecked();
        
        int hour = timePicker.getCurrentHour();
        int minute = timePicker.getCurrentMinute();
        String notificationTime = String.format(Locale.CHINA, "%02d:%02d", hour, minute);
        
        // 保存设置
        FortuneApplication app = FortuneApplication.getInstance();
        app.saveNotificationSettings(notificationsEnabled, notificationTime);
        
        // 更新通知设置
        if (notificationsEnabled) {
            NotificationHelper.scheduleDailyReminder(getActivity());
        } else {
            NotificationHelper.cancelDailyReminder(getActivity());
        }
        
        // 更新状态
        tvSettingsStatus.setText("设置已保存");
        tvSettingsStatus.setVisibility(View.VISIBLE);
        
        // 延迟隐藏状态
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                if (isAdded()) {
                    tvSettingsStatus.setVisibility(View.GONE);
                }
            }
        }, 3000);
    }
    
    /**
     * 加载用户信息
     */
    private void loadUserInfo() {
        FortuneApplication app = FortuneApplication.getInstance();
        
        if (app.isUserInfoSet()) {
            etName.setText(app.getUserName());
            etBirthDate.setText(app.getUserBirthDate());
            etGender.setText(app.getUserGender());
        }
    }
    
    /**
     * 加载设置
     */
    private void loadSettings() {
        FortuneApplication app = FortuneApplication.getInstance();
        
        switchNotification.setChecked(app.isNotificationsEnabled());
        
        String notificationTime = app.getNotificationTime();
        if (notificationTime != null && !notificationTime.isEmpty()) {
            String[] timeParts = notificationTime.split(":");
            if (timeParts.length == 2) {
                int hour = Integer.parseInt(timeParts[0]);
                int minute = Integer.parseInt(timeParts[1]);
                timePicker.setCurrentHour(hour);
                timePicker.setCurrentMinute(minute);
            }
        }
    }
}
